package com.kt.emall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.kt.common.constant.AuthServerConstant;
import com.kt.common.exception.BizCodeEnum;
import com.kt.common.utils.R;
import com.kt.common.vo.MemberRespVO;
import com.kt.emall.auth.feign.MemberFeignService;
import com.kt.emall.auth.feign.ThirdPartFeignService;
import com.kt.emall.auth.vo.UserLoginVO;
import com.kt.emall.auth.vo.UserRegVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program: e-mall
 * @description: 登录注册Controller
 * @author: KamTang
 * @create: 2022-01-11 08:50
 **/
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送一个请求直接跳转到一个页面
     * SpringMVC ViewControllers 将请求和页面映射过来
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        // TODO 1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CATCH_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long redisTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - redisTime < 60000) {
                // 60s内不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        // 2、验证码再次校验 -> redis：以key-phone, value-code形式存入redis   sms:code:手机号 -> code
        // redis缓存验证码，防止同一个phone在60s内再次发送验证码
        String code = UUID.randomUUID().toString().substring(0, 5);
        String substring = code + "_" + System.currentTimeMillis();
        // 验证码10min有效
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CATCH_PREFIX + phone, substring, 10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     *
     * @param vo 前端传来的用户输入数据
     * @param bindingResult 自定义校验结果
     * @param redirectAttributes 模拟重定向携带数据 原理：session
     *                           只要跳转到下一个页面，取出数据以后，session里面的数据就会被删除
     *                           // TODO 分布式下的session问题
     * @return
     */
    @PostMapping("/register")
    public String register(@Valid UserRegVO vo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            /**
             * .map(fieldError -> {
             *                 String errorField = fieldError.getField();
             *                 String defaultMessage = fieldError.getDefaultMessage();
             *                 errorsMap.put(errorField, defaultMessage);
             *                 return errorsMap;
             *             });
             */
            Map<String, String> errorsMap = bindingResult.getFieldErrors().
                    stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errorsMap", errorsMap);
            // Request method 'POST' not supported
            // 用户注册 -> /register[post] --> 转发/reg.html(路径映射默认都是get方式访问的)

            // 校验出错，转发到注册页面
            // 重定向处理刷新页面造成的表单重复提交的问题
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 真正注册，需要调用远程服务。
        // 1、校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CATCH_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                // 删除验证码（令牌机制）
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CATCH_PREFIX + vo.getPhone());
                // 验证码正确，真正注册，调用远程服务进行注册
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
                    // 成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, String> errorsMap = new HashMap<>();
                    errorsMap.put("msg", r.getData("msg", new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errorsMap", errorsMap);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                Map<String, String> errorsMap = new HashMap<>();
                errorsMap.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errorsMap", errorsMap);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errorsMap = new HashMap<>();
            errorsMap.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errorsMap", errorsMap);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @GetMapping("/login.html")
    public String toLoginPage(HttpSession session) {
        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser == null) {
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVO userLoginVO, RedirectAttributes redirectAttributes, HttpSession session) {
        // 远程登录
        R r = memberFeignService.login(userLoginVO);
        if (r.getCode() == 0) {
            // success
            MemberRespVO memberRespVO = r.getData("data", new TypeReference<MemberRespVO>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVO);
            return "redirect:http://gulimall.com";
        } else {
            // error
            Map<String, String> errorsMap = new HashMap<>();
            errorsMap.put("msg", r.getData("msg", new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errorsMap", errorsMap);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

}
